<template>
    <main style="display: flex; height: 100vh;">
        <!-- 左侧控制面板 -->
        <LeftControlPanel :statistics="dataCenterStore.getStatistics()" @start-add-row="activeForm = 'row'"
            @clear-all="dataCenterStore.clearAll()">
            <!-- 表单插槽 -->
            <AddRowForm v-if="activeForm === 'row'" @submit="handleAddRow" @cancel="activeForm = null" />
            <AddCabinetForm v-if="activeForm === 'rowCabinet'" :row-id="selectedRowId" @submit="handleAddCabinet"
                @cancel="activeForm = null" />

            <!-- 元素列表 -->
            <ElementsList :rows="dataCenterStore.rows as any" :selected-cabinet-id="selectedCabinet?.id || null"
                @add-cabinet-to-row="startAddCabinetToRow" @remove-row="dataCenterStore.removeRow"
                @select-cabinet="onCabinetSelected" @remove-cabinet="handleRemoveCabinet" />
        </LeftControlPanel>

        <!-- 3D场景 -->
        <div class="scene" style="flex: 1; background-color: var(--color-background);">
            <DataCenter3DRenderer @cabinet-selected="onCabinetSelected" @device-selected="onDeviceSelected" />
        </div>

        <!-- 右侧属性面板 -->
        <RightPropertiesPanel :selected-cabinet="selectedCabinet as any" :selected-device="selectedDevice as any"
            @deselect-cabinet="selectedCabinet = null" @deselect-device="selectedDevice = null"
            @delete-cabinet="handleDeleteCabinet" @delete-device="handleDeleteDevice" />
    </main>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { useDataCenterStore } from '@/stores/datacenter'
import type { Cabinet } from '@/stores/datacenter'
import DataCenter3DRenderer from '@/components/DataCenter3DRenderer.vue'
import LeftControlPanel from '@/components/LeftControlPanel.vue'
import RightPropertiesPanel from '@/components/RightPropertiesPanel.vue'
import ElementsList from '@/components/ElementsList.vue'
import AddRowForm from '@/components/AddRowForm.vue'
import AddCabinetForm from '@/components/AddCabinetForm.vue'

const dataCenterStore = useDataCenterStore()

// Form states
const activeForm = ref<'row' | 'rowCabinet' | null>(null)
const selectedRowId = ref<string>('')

// 选中的机柜状态
const selectedCabinet = ref<Cabinet | null>(null)
const selectedDevice = ref<any | null>(null)

const handleAddRow = (rowData: any) => {
    const row = dataCenterStore.addRow({
        name: rowData.name,
        description: rowData.description,
        position: rowData.position,
        spacing: rowData.spacing,
        color: rowData.color
    })

    for (let i = 0; i < rowData.cabinetCount; i++) {
        row.addCabinet({
            name: `${rowData.name}${i + 1}`,
            description: `${rowData.name}${i + 1}`,
            width: rowData.cabinetWidth,
            color: rowData.cabinetColor,
            type: rowData.cabinetType
        })
    }

    activeForm.value = null
}

const handleAddCabinet = (cabinetData: any) => {
    if (selectedRowId.value) {
        const row = dataCenterStore.findRowById(selectedRowId.value)
        if (row) {
            const cabinetName = generateNextCabinetName(row.name, row.cabinets)
            row.addCabinet({
                name: cabinetName,
                description: cabinetData.description || `${row.name}列中的机柜`,
                width: cabinetData.width,
                color: cabinetData.color,
                type: cabinetData.type
            })
        }
        activeForm.value = null
        selectedRowId.value = ''
    }
}

const startAddCabinetToRow = (rowId: string) => {
    selectedRowId.value = rowId
    activeForm.value = 'rowCabinet'
}

const handleRemoveCabinet = (rowId: string, cabinetId: string) => {
    const row = dataCenterStore.findRowById(rowId)
    if (row) {
        row.removeCabinet(cabinetId)
        if (selectedCabinet.value?.id === cabinetId) {
            selectedCabinet.value = null
        }
    }
}

// 机柜选择回调函数
const onCabinetSelected = (cabinetId: string | null) => {
    if (cabinetId) {
        const cabinet = dataCenterStore.findCabinetById(cabinetId)
        selectedCabinet.value = cabinet || null
    } else {
        selectedCabinet.value = null
    }
}

// 生成下一个机柜名称
const generateNextCabinetName = (rowName: string, existingCabinets: any[]) => {
    const maxNumber = existingCabinets
        .map(cabinet => {
            const match = cabinet.name.match(new RegExp(`^${rowName}(\\d+)$`))
            return match ? parseInt(match[1]) : 0
        })
        .reduce((max, num) => Math.max(max, num), 0)

    return `${rowName}${maxNumber + 1}`
}

const onDeviceSelected = (deviceId: string | null, cabinetId: string | null) => {
    if (deviceId && cabinetId) {
        // 查找设备
        for (const row of dataCenterStore.rows) {
            const cabinet = row.cabinets.find(cab => cab.id === cabinetId)
            if (cabinet) {
                const device = cabinet.devices.find(d => d.id === deviceId)
                selectedDevice.value = device || null
                selectedCabinet.value = null // 清除机柜选中状态
                return
            }
        }
    }
    selectedDevice.value = null
}

const handleDeleteCabinet = (cabinetId: string) => {
    handleRemoveCabinet('', cabinetId) // 复用现有逻辑
}

const handleDeleteDevice = (deviceId: string, cabinetId: string) => {
    console.log('主Dashboard接收到删除设备请求:', deviceId, cabinetId)

    const row = dataCenterStore.rows.find(r => r.cabinets.some(c => c.id === cabinetId))
    if (row) {
        const cabinet = row.cabinets.find(c => c.id === cabinetId)
        if (cabinet) {
            console.log('找到机柜，正在删除设备:', cabinet.name, deviceId)
            const success = cabinet.removeDevice(deviceId)
            console.log('删除设备结果:', success)
            selectedDevice.value = null
        } else {
            console.log('未找到指定的机柜:', cabinetId)
        }
    } else {
        console.log('未找到包含指定机柜的行:', cabinetId)
    }
}

</script>